package com.spit.tph.nike_mvp.weight

import CONSUMABLES_RECEIVE
import CONSUMABLES_RESTOCK
import CONSUMABLES_WAREHOUSE
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.AppCompatButton
import android.support.v7.widget.AppCompatEditText
import android.support.v7.widget.AppCompatSpinner
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.spit.tph.R
import com.spit.tph.nike_mvp.base.BaseFullBottomSheetFragment
import com.spit.tph.nike_mvp.utils.ToastUtil
import com.yyc.stocktake.bean.DataBean
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 * User: Nike
 *  2024/3/7 17:08
 */
class ConsumablesConfigFrg: BaseFullBottomSheetFragment(), View.OnClickListener {

    var listBean = ArrayList<DataBean>()

    //团队列表
    var listTeamBean = ArrayList<DataBean>()

    //仓库列表
    var listWarehouseBean = ArrayList<DataBean>()

    //物资列表
    var listMaterialBean = ArrayList<DataBean>()

    //医疗师列表
    var listTherapistBean = ArrayList<DataBean>()

    var mEtReceive: AppCompatEditText? = null
    var mEtRemark: AppCompatEditText? = null
    var mEtNumber: AppCompatEditText? = null
    var mEtWard: AppCompatEditText? = null
    var mEtBed: AppCompatEditText? = null

    lateinit var mSpWarehouse: AppCompatSpinner
    lateinit var mSpTeam: AppCompatSpinner
    lateinit var mSpMaterial: AppCompatSpinner
    lateinit var mSpTherapists: AppCompatSpinner

    var mCStatus = -1//选中状态

    private var scanText: String? = null
    fun setScanText(s: String){
        this.scanText = s
        mEtNumber?.setText(scanText)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.p_c_config, container, false)
        if (arguments != null) {
            mCStatus = arguments!!.getInt("mCStatus")
            val listType = object : TypeToken<List<DataBean>>() {}.type
            listBean = Gson().fromJson<List<DataBean>>(arguments!!.getString("listBean"), listType) as ArrayList<DataBean>
            listTeamBean = Gson().fromJson<List<DataBean>>(arguments!!.getString("listTeamBean"), listType) as ArrayList<DataBean>
            listWarehouseBean = Gson().fromJson<List<DataBean>>(arguments!!.getString("listWarehouseBean"), listType) as ArrayList<DataBean>
            listMaterialBean = Gson().fromJson<List<DataBean>>(arguments!!.getString("listMaterialBean"), listType) as ArrayList<DataBean>
            listTherapistBean = Gson().fromJson<List<DataBean>>(arguments!!.getString("listTherapistBean"), listType) as ArrayList<DataBean>
        }
        rootView.findViewById<AppCompatButton>(R.id.bt_cancel).setOnClickListener(this)
        rootView.findViewById<AppCompatButton>(R.id.bt_confirm).setOnClickListener(this)
        rootView.findViewById<FrameLayout>(R.id.fy_scan).setOnClickListener(this)
        val ly_receive = rootView.findViewById<LinearLayout>(R.id.ly_receive)
        val ly_warehouse = rootView.findViewById<LinearLayout>(R.id.ly_warehouse)
        val ly_team = rootView.findViewById<LinearLayout>(R.id.ly_team)
        mSpTeam = rootView.findViewById(R.id.sp_team)
        mSpWarehouse = rootView.findViewById(R.id.sp_warehouse)
        mSpMaterial = rootView.findViewById(R.id.sp_material)
        mSpTherapists = rootView.findViewById(R.id.sp_therapists)
        mEtReceive = rootView.findViewById(R.id.et_receive)
        mEtRemark = rootView.findViewById(R.id.et_remark)
        mEtNumber = rootView.findViewById(R.id.et_number)
        mEtWard = rootView.findViewById(R.id.et_ward)
        mEtBed = rootView.findViewById(R.id.et_bed)

        when (mCStatus) {
            CONSUMABLES_RECEIVE -> {
                ly_receive.visibility = View.VISIBLE
                ly_team.visibility = View.VISIBLE
                val bean = DataBean()
                bean.dataName = "-"
                listTeamBean.add(bean)
                mSpTeam.adapter = CustomSpinnerAdapter(requireContext(), listTeamBean)
                mSpTeam.setSelection(listTeamBean.size - 1)

                val materialBean = DataBean()
                materialBean.dataName = "-"
                listMaterialBean.add(materialBean)
                mSpMaterial.adapter = CustomSpinnerAdapter(requireContext(), listMaterialBean)
                mSpMaterial.setSelection(listMaterialBean.size - 1)

                var therapistsBean = DataBean()
                therapistsBean.dataName = "-"
                listTherapistBean.add(therapistsBean)
                mSpTherapists.adapter = CustomSpinnerAdapter(requireContext(), listTherapistBean)
                mSpTherapists.setSelection(listTherapistBean.size - 1)
            }
            CONSUMABLES_WAREHOUSE ->{
                ly_warehouse.visibility = View.VISIBLE
                val bean = DataBean()
                bean.dataName = "-"
                listWarehouseBean.add(bean)
                mSpWarehouse.adapter = CustomSpinnerAdapter(requireContext(), listWarehouseBean)
                mSpWarehouse.setSelection(listWarehouseBean.size - 1)
            }
            CONSUMABLES_RESTOCK ->{
                ly_warehouse.visibility = View.VISIBLE
                ly_receive.visibility = View.VISIBLE
                val bean = DataBean()
                bean.dataName = "-"
                listWarehouseBean.add(bean)
                mSpWarehouse.adapter = CustomSpinnerAdapter(requireContext(), listWarehouseBean)
                mSpWarehouse.setSelection(listWarehouseBean.size - 1)

                val materialBean = DataBean()
                materialBean.dataName = "-"
                listMaterialBean.add(materialBean)
                mSpMaterial.adapter = CustomSpinnerAdapter(requireContext(), listMaterialBean)
                mSpMaterial.setSelection(listMaterialBean.size - 1)
            }
        }

        return rootView
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.fy_scan ->{
                mListener?.onWarehouseScanCallback()
            }
            R.id.bt_confirm ->{
                val receive = mEtReceive?.text.toString()
                val remark = mEtRemark?.text.toString()
                val number = mEtNumber?.text.toString()
                val ward = mEtWard?.text.toString()
                val bed = mEtBed?.text.toString()
                var teamBean: DataBean? = null
                var therapistsBean: DataBean? = null
                var materialBean: DataBean?
                var warehouseBean: DataBean?
                when(mCStatus){
                    CONSUMABLES_RECEIVE ->{
                        /*if (mSpTherapists.selectedItemPosition == listTherapistBean.size - 1){
                            ToastUtil.showShortToast( requireActivity().getString(R.string.text20))
                            return
                        }*/
                        if (mSpTherapists.selectedItemPosition != listTherapistBean.size - 1){
                            therapistsBean = listTherapistBean[mSpTherapists.selectedItemPosition]
                        }
                        if (mSpMaterial.selectedItemPosition == listMaterialBean.size - 1){
                            ToastUtil.showShortToast( requireActivity().getString(R.string.text5))
                            return
                        }
                        materialBean = listMaterialBean[mSpMaterial.selectedItemPosition]
                        /*if (mSpTeam.selectedItemPosition == listTeamBean.size - 1){
                            ToastUtil.showShortToast( requireActivity().getString(R.string.text4))
                            return
                        }*/
                        if (mSpTeam.selectedItemPosition != listTeamBean.size - 1){
                            teamBean = listTeamBean[mSpTeam.selectedItemPosition]
                        }
                        val jsonArray = JSONArray()
                        listBean.forEachIndexed { index, dataBean ->
                            dataBean.remark = dataBean.remark.takeUnless { it.isEmpty() } ?: remark
                            val obj = JSONObject()
                            obj.put("rono", dataBean.rono)
                            obj.put("changeFlag", mCStatus)
                            obj.put("changeQuantity", dataBean.num)
                            obj.put("changeDate", getCurrentTimeString())
                            obj.put("changeRemarks", dataBean.remark)
                            obj.put("patientId", number)
                            obj.put("changeMethod", if (mCStatus == CONSUMABLES_RECEIVE) 0 else 1)
                            obj.put("mtRoNo", teamBean?.rono)
                            obj.put("changeLocation", materialBean?.rono)
                            obj.put("therapist", therapistsBean?.rono)
                            obj.put("ward", ward)
                            obj.put("bedNumber", bed)
                            jsonArray.put(obj)
                        }
                        val obj = JSONObject()
                        obj.put("consumables", jsonArray)
                        mListener?.onSubmitCallback(obj.toString(), listBean)
                    }
                    CONSUMABLES_WAREHOUSE ->{
                        if (mSpWarehouse.selectedItemPosition == listWarehouseBean.size - 1){
                            ToastUtil.showShortToast(requireActivity().getString(R.string.text3))
                            return
                        }
                        warehouseBean = listWarehouseBean[mSpWarehouse.selectedItemPosition]
                        val jsonArray = JSONArray()
                        listBean.forEachIndexed { index, dataBean ->
                            dataBean.remark = dataBean.remark.takeUnless { it.isEmpty() } ?: remark
                            val obj = JSONObject()
                            obj.put("rono", dataBean.rono)
                            obj.put("changeFlag", mCStatus)
                            obj.put("changeQuantity", dataBean.num)
                            obj.put("changeDate", getCurrentTimeString())
                            obj.put("changeRemarks", dataBean.remark)
                            obj.put("changeMethod", if (mCStatus == CONSUMABLES_RECEIVE) 0 else 1)
                            obj.put("changeLocation", warehouseBean?.rono)
                            jsonArray.put(obj)
                        }
                        val obj = JSONObject()
                        obj.put("consumables", jsonArray)
                        Log.e("", obj.toString())
                        mListener?.onSubmitCallback(obj.toString(), listBean)
                    }
                    CONSUMABLES_RESTOCK ->{
                        if (mSpWarehouse.selectedItemPosition == listWarehouseBean.size - 1){
                            ToastUtil.showShortToast(requireActivity().getString(R.string.text3))
                            return
                        }
                        warehouseBean = listWarehouseBean[mSpWarehouse.selectedItemPosition]
                        if (mSpMaterial.selectedItemPosition == listMaterialBean.size - 1){
                            ToastUtil.showShortToast( requireActivity().getString(R.string.text5))
                            return
                        }
                        materialBean = listMaterialBean[mSpMaterial.selectedItemPosition]
                        val jsonArray = JSONArray()
                        listBean.forEachIndexed { index, dataBean ->
                            dataBean.remark = dataBean.remark.takeUnless { it.isEmpty() } ?: remark
                            val obj = JSONObject()
                            obj.put("rono", dataBean.rono)
                            obj.put("changeFlag", mCStatus)
                            obj.put("changeQuantity", dataBean.num)
                            obj.put("changeDate", getCurrentTimeString())
                            obj.put("changeRemarks", dataBean.remark)
                            obj.put("changeMethod", if (mCStatus == CONSUMABLES_RECEIVE) 0 else 1)
                            obj.put("changeLocation", warehouseBean?.rono)
                            obj.put("mLocation", materialBean?.rono)
                            jsonArray.put(obj)
                        }
                        val obj = JSONObject()
                        obj.put("consumables", jsonArray)
                        Log.e("", obj.toString())
                        mListener?.onSubmitCallback(obj.toString(), listBean)
                    }
                }
                dismiss()
            }
            R.id.bt_cancel -> {
                dismiss()
            }
        }
    }

    class CustomSpinnerAdapter(context: Context, data: ArrayList<DataBean>) :
        ArrayAdapter<DataBean>(context, R.layout.i_spinner_text, data) {

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view = super.getView(position, convertView, parent)
            val tv = view.findViewById<TextView>(R.id.tv_text)
            tv.text = getItem(position)?.dataName
            return view
        }

        override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view = super.getDropDownView(position, convertView, parent)
            val tv = view.findViewById<TextView>(R.id.tv_text)
            tv.text = getItem(position)?.dataName
            return view
        }
    }

    private var mListener: OnClickListener? = null

    fun setOnClickListener(l: OnClickListener) {
        mListener = l
    }

    interface OnClickListener {
        fun onSubmitCallback(json: String, listBean: ArrayList<DataBean>)
        fun onWarehouseScanCallback()
    }

    fun getCurrentTimeString(): String {
        val calendar = Calendar.getInstance()
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return dateFormat.format(calendar.time)
    }

}